local basic = require("luaScript.module.common.basic");
local redisOp = require("luaScript.redis.RedisOperator");

local PREFIX = "GOOD_CACHE:"

local _RedisCacheDemo = {};
_RedisCacheDemo.__index = _RedisCacheDemo;

-- 构造函数
function _RedisCacheDemo.new(self)
    local cls = {};
    setmetatable(cls, self);
    return cls;
end

-- 获取参数名字
function _RedisCacheDemo.getParameter(self, parameterName)
    local request_method = ngx.var.request_method;
    local args = nil;
    if request_method == "GET" then
        args = ngx.req.get_uri_args();
    elseif request_method == "POST" then
        ngx.req.read_body();
        args = ngx.req.get_post_args();
    end
    return args[parameterName];
end

-- 获取缓存
function _RedisCacheDemo.getCache(self, skuId)
    local redis = redisOp:new();
    if not redis:open() then
        basic.log("redis连接失败");
        return nil;
    end

    local json = redis:getValue(PREFIX .. skuId);
    redis:close();
    if not json or json == ngx.null then
        basic.log("缓存命中失败");
        return nil;
    end
    basic.log("缓存命中成功");
    return json;
end

-- 优先从缓存获取，否则回源上游接口
function _RedisCacheDemo.goUpstream(self, url)
    local request_method = ngx.var.request_method;
    local args = nil;
    if request_method == "GET" then
        args = ngx.req.get_uri_args();
    elseif request_method == "POST" then
        ngx.req.read_body();
        args = ngx.req.get_post_args();
    end

    local res = ngx.location.capture(url, {
        method = ngx.HTTP_GET,
        args = args  -- 重要：将请求参数，原样向上游传递
    });
    basic.log("上游数据获取成功");
    return res.body;
end

-- 设置缓存
function _RedisCacheDemo.setCache(self, skuId, skuJson)
    local redis = redisOp:new();
    if not redis:open() then
        basic.log("redis连接失败");
        return nil;
    end

    redis:setValue(PREFIX .. skuId, skuJson);
    -- 60秒过期
    redis:expire(PREFIX .. skuId, 60);
    basic.log(skuId .. "缓存设置成功");
    redis:close();
    return skuJson;
end

return _RedisCacheDemo;